<template>
  <el-form
      :model="form"
      label-position="top"
      :rules="rules"
      @submit.prevent="handleSubmit"
      ref="formRef"
      class="calculator-form"
  >
    <!-- 科目成绩输入区域 -->
    <div class="scores-section">
      <div class="section-header">
        <div class="section-icon">📚</div>
        <div class="section-title">
          <h4>科目成绩</h4>
          <p>请输入各科目的考试成绩</p>
        </div>
      </div>

      <div class="scores-grid">
        <div
            v-for="subject in subjects"
            :key="subject.name"
            class="score-item"
        >
          <div class="score-label">
            <span class="subject-name">{{ subject.name }}</span>
            <span class="score-max">满分 {{ subject.full }} 分</span>
          </div>
          <el-input-number
              v-model.number="form.scores[subject.name]"
              :max="subject.full"
              :min="0"
              controls-position="right"
              class="score-input"
              :placeholder="`请输入${subject.name}分数`"
              size="large"
          />
        </div>
      </div>
    </div>

    <!-- 排名输入区域 -->
    <div class="rank-section">
      <div class="section-header">
        <div class="section-icon">🏆</div>
        <div class="section-title">
          <h4>排名信息</h4>
          <p>请输入当前排名</p>
        </div>
      </div>

      <div class="rank-input-container">
        <el-input-number
            v-model.number="form.currentRank"
            :min="1"
            controls-position="right"
            class="rank-input"
            placeholder="请输入当前排名"
            size="large"
        />
        <div class="rank-hint">
          <el-icon>
            <InfoFilled/>
          </el-icon>
          <span>排名越小，奖励越高</span>
        </div>
      </div>
    </div>

    <!-- 提交按钮 -->
    <div class="submit-section">
      <div class="button-group">
        <el-button
            type="primary"
            :loading="loading"
            class="submit-btn"
            size="large"
            @click="handleSubmit"
        >
          <template v-if="!loading">
            <Calculator theme="outline" size="20" fill="#fff" style="margin-right: 6px;"/>
          </template>
          <span>{{ loading ? '计算中...' : '开始计算' }}</span>
        </el-button>

        <el-button
            type="warning"
            :icon="Delete"
            @click="handleClearForm"
            class="clear-btn"
            size="large"
            :disabled="loading"
        >
          清空数据
        </el-button>
      </div>
    </div>
  </el-form>
</template>

<script>
import {InfoFilled, Delete} from '@element-plus/icons-vue'
import {Calculator} from '@icon-park/vue-next'

export default {
  name: 'CalculatorForm',
  computed: {
    Delete() {
      return Delete
    }
  },
  components: {
    InfoFilled,
    Calculator
  },
  props: {
    subjects: {
      type: Array,
      required: true
    },
    loading: {
      type: Boolean,
      default: false
    },
    isMobile: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      form: {
        scores: {},
        currentRank: null,
        previousRank: null,
        previousMetBase: false
      },
      rules: {
        currentRank: [
          {required: true, message: '请填写当前排名', trigger: 'blur'},
          {type: 'number', message: '排名必须是数字', trigger: 'blur'}
        ]
      }
    }
  },
  methods: {
    validateScores(_, value, callback) {
      if (!value || Object.keys(value).length === 0) {
        return callback(new Error('请填写所有科目成绩'))
      }

      const emptySubjects = this.subjects
          .filter(sub => {
            const score = value[sub.name]
            return score === '' || score == null || isNaN(score)
          })
          .map(sub => `${sub.name}未填写`)

      const overfullSubjects = this.subjects
          .filter(sub => {
            const score = value[sub.name]
            return !isNaN(score) && Number(score) > sub.full
          })
          .map(sub => `${sub.name}超出${sub.full}分`)

      const allErrors = [...emptySubjects, ...overfullSubjects]

      if (allErrors.length) {
        callback(new Error(allErrors.join('，')))
      } else {
        callback()
      }
    },
    validateForm() {
      return new Promise((resolve, reject) => {
        this.validateScores(null, this.form.scores, (err) => {
          if (err) {
            reject(err)
          } else {
            this.$refs.formRef.validateField('currentRank', (errMsg) => {
              if (typeof errMsg === 'string' && errMsg) {
                reject(new Error(errMsg))
              } else {
                resolve(true)
              }
            })
          }
        })
      })
    },
    async handleSubmit() {
      console.log('✅ handleSubmit 触发了');
      try {
        await this.validateForm()
      } catch (e) {
        console.log('❌ handleSubmit 触发了错误', e);
        this.$message({
          message: e.message || '表单校验失败，请检查填写内容',
          type: 'error',
          duration: 4000,
          showClose: true,
          iconClass: 'el-icon-warning-outline',
        });
        return
      }

      this.$emit('form-submit', this.form)
    },
    handleClearForm() {
      this.$emit('clear')
    },
    clearForm() {
      this.form = {
        scores: this.subjects.reduce((acc, subject) => {
          acc[subject.name] = null
          return acc
        }, {}),
        currentRank: null,
        previousRank: null,
        previousMetBase: false
      }
      this.$refs.formRef?.clearValidate()
    },
    loadFormData(data) {
      this.form = {...data}
    }
  },
  watch: {
    subjects: {
      immediate: true,
      handler(newSubjects) {
        if (newSubjects.length > 0) {
          this.form.scores = newSubjects.reduce((acc, subject) => {
            acc[subject.name] = null
            return acc
          }, {})
        }
      }
    }
  }
}
</script>

<style scoped>
.calculator-form {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-xl);
}

/* 区域样式 */
.scores-section,
.rank-section {
  background: rgba(255, 255, 255, 0.8);
  border-radius: var(--border-radius-small);
  padding: var(--spacing-lg);
  border: 1px solid rgba(255, 255, 255, 0.3);
  backdrop-filter: var(--backdrop-blur-light);
  transition: var(--transition-base);
}

.scores-section:hover,
.rank-section:hover {
  background: rgba(255, 255, 255, 0.9);
  transform: translateY(-1px);
  box-shadow: var(--shadow-light);
}

/* 区域头部 */
.section-header {
  display: flex;
  align-items: center;
  gap: var(--spacing-md);
  margin-bottom: var(--spacing-lg);
}

.section-icon {
  font-size: var(--font-size-2xl);
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--gradient-page);
  color: white;
  border-radius: var(--border-radius-small);
  box-shadow: var(--shadow-light);
}

.section-title h4 {
  margin: 0 0 var(--spacing-xs) 0;
  font-size: var(--font-size-lg);
  font-weight: 600;
  color: var(--text-primary);
}

.section-title p {
  margin: 0;
  color: var(--text-light);
  font-size: var(--font-size-base);
}

/* 成绩网格 */
.scores-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: var(--spacing-md);
}

.score-item {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-sm);
  padding: var(--spacing-md);
  background: rgba(255, 255, 255, 0.6);
  border-radius: var(--border-radius-small);
  border: 1px solid rgba(255, 255, 255, 0.4);
  transition: var(--transition-fast);
}

.score-item:hover {
  background: rgba(255, 255, 255, 0.8);
  transform: translateY(-2px);
  box-shadow: var(--shadow-light);
}

.score-label {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.subject-name {
  font-weight: 600;
  color: var(--text-primary);
  font-size: var(--font-size-base);
}

.score-max {
  color: var(--text-light);
  font-size: var(--font-size-sm);
  background: rgba(103, 194, 58, 0.1);
  padding: 2px 8px;
  border-radius: 12px;
}

.score-input {
  width: 100%;
}

.score-input :deep(.el-input-number__decrease),
.score-input :deep(.el-input-number__increase) {
  background: var(--primary-color);
  color: white;
  border: none;
  transition: var(--transition-fast);
}

.score-input :deep(.el-input-number__decrease:hover),
.score-input :deep(.el-input-number__increase:hover) {
  background: #66b1ff;
  transform: scale(1.1);
}

/* 排名区域 */
.rank-input-container {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-md);
}

.rank-input {
  width: 100%;
  max-width: 300px;
}

.rank-hint {
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
  color: var(--text-light);
  font-size: var(--font-size-sm);
  padding: var(--spacing-sm);
  background: rgba(64, 158, 255, 0.1);
  border-radius: var(--border-radius-small);
  border-left: 3px solid var(--primary-color);
}

.rank-hint .el-icon {
  color: var(--primary-color);
}

/* 提交区域 */
.submit-section {
  display: flex;
  justify-content: center;
  padding: var(--spacing-lg) 0;
}

.button-group {
  display: flex;
  gap: var(--spacing-md);
  justify-content: center;
}

.submit-btn {
  min-width: 200px;
  height: 56px;
  font-size: var(--font-size-lg);
  font-weight: 600;
  border-radius: var(--border-radius);
  background: var(--gradient-primary);
  border: none;
  box-shadow: var(--shadow-medium);
  transition: var(--transition-base);
  display: flex;
  align-items: center;
  justify-content: center;
  gap: var(--spacing-sm);
}

.submit-btn:hover {
  transform: translateY(-3px);
  box-shadow: var(--shadow-heavy);
  background: var(--gradient-primary-reverse);
}

.submit-btn:active {
  transform: translateY(-1px);
}

.submit-btn .el-icon {
  font-size: var(--font-size-lg);
}

.clear-btn {
  min-width: 150px;
  height: 56px;
  font-size: var(--font-size-lg);
  font-weight: 600;
  border-radius: var(--border-radius);
  background: var(--gradient-danger);
  border: none;
  box-shadow: var(--shadow-medium);
  transition: var(--transition-base);
  display: flex;
  align-items: center;
  justify-content: center;
  gap: var(--spacing-sm);
}

.clear-btn:hover {
  transform: translateY(-3px);
  box-shadow: var(--shadow-heavy);
  background: var(--gradient-danger-reverse);
}

.clear-btn:active {
  transform: translateY(-1px);
}

.clear-btn .el-icon {
  font-size: var(--font-size-lg);
}

/* 响应式设计 */
@media screen and (max-width: 1200px) {
  .calculator-form {
    gap: var(--spacing-lg);
  }
  
  .scores-grid {
    grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
    gap: var(--spacing-md);
  }
  
  .button-group {
    gap: var(--spacing-md);
  }
}

@media screen and (max-width: 768px) {
  .calculator-form {
    gap: var(--spacing-md);
  }

  .scores-section,
  .rank-section {
    padding: var(--spacing-md);
  }

  .section-header {
    flex-direction: column;
    text-align: center;
    gap: var(--spacing-sm);
  }

  .section-icon {
    width: 40px;
    height: 40px;
    font-size: var(--font-size-xl);
  }
  
  .section-title h4 {
    font-size: var(--font-size-lg);
  }
  
  .section-title p {
    font-size: var(--font-size-sm);
  }

  .scores-grid {
    grid-template-columns: 1fr;
    gap: var(--spacing-sm);
  }

  .score-item {
    padding: var(--spacing-sm);
  }
  
  .score-label {
    font-size: var(--font-size-base);
  }
  
  .score-input {
    font-size: var(--font-size-base);
  }

  .rank-input {
    max-width: none;
  }
  
  .rank-hint {
    font-size: var(--font-size-sm);
    padding: var(--spacing-sm);
  }

  .button-group {
    flex-direction: column;
    gap: var(--spacing-sm);
  }

  .submit-btn,
  .clear-btn {
    min-width: 100%;
    height: 48px;
    font-size: var(--font-size-base);
  }
}

@media screen and (max-width: 480px) {
  .calculator-form {
    gap: var(--spacing-sm);
  }
  
  .scores-section,
  .rank-section {
    padding: var(--spacing-sm);
    border-radius: var(--border-radius-small);
  }

  .section-header {
    gap: var(--spacing-xs);
    padding: var(--spacing-sm) 0;
  }
  
  .section-icon {
    width: 36px;
    height: 36px;
    font-size: var(--font-size-lg);
  }

  .section-title h4 {
    font-size: var(--font-size-base);
    margin-bottom: var(--spacing-xs);
  }

  .section-title p {
    font-size: var(--font-size-xs);
    line-height: 1.3;
  }

  .scores-grid {
    gap: var(--spacing-xs);
  }
  
  .score-item {
    padding: var(--spacing-xs);
    border-radius: var(--border-radius-mini);
  }

  .score-label {
    flex-direction: column;
    align-items: flex-start;
    gap: var(--spacing-xs);
    font-size: var(--font-size-sm);
  }
  
  .score-input {
    font-size: var(--font-size-sm);
    height: 40px;
  }
  
  .score-input :deep(.el-input__wrapper) {
    padding: 0 var(--spacing-sm);
  }

  .rank-input {
    height: 40px;
  }
  
  .rank-input :deep(.el-input__wrapper) {
    padding: 0 var(--spacing-sm);
  }
  
  .rank-hint {
    font-size: var(--font-size-xs);
    padding: var(--spacing-xs);
    border-radius: var(--border-radius-mini);
  }
  
  .button-group {
    gap: var(--spacing-xs);
  }

  .submit-btn,
  .clear-btn {
    height: 44px;
    font-size: var(--font-size-sm);
    border-radius: var(--border-radius-small);
  }
  
  .submit-btn .el-icon,
  .clear-btn .el-icon {
    font-size: var(--font-size-base);
  }
}
</style> 